<?php
declare (strict_types = 1);

// +----------------------------------------------------------------------
// | Saruri
// +----------------------------------------------------------------------
// | 版权所有 2020~2021 系统集成中国有限公司 [ http://www.saruri.cn ]
// +----------------------------------------------------------------------
// | 官方网站: https://saruri.cn
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/saruri/saruri.git
// | github 代码仓库：https://github.com/sarurifan/saruri.git
// +----------------------------------------------------------------------

namespace app\client\controller;

use think\Request;
use app\admin\libs\CommonController;
use app\admin\service\ClientService;

/**
 * 代码生成的Client 控制器
 * Class Client 
 * @package app\admin\controller
 */
class Client extends CommonController 
{
    
	
		
	/* 
	*  @desc      客户端
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 14:26:15  
	*/ 
	public function  build(array $arr)
	{
		$this->buildController($arr);
		$this->buildSchema($arr);
		$this->buildService($arr);
		$this->buildApi($arr);
		$this->buildView($arr,'index');
		$this->buildView($arr,'form');

		$this->checkAll($arr);
		$this->buildFileAll();
	}
	


	/* 
	*  @desc      检查全部
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/08 10:05:41  
	*/ 
	public function  checkAll(array $arr)
	{
		$str='';
		$sql=$this->checkSql($arr);

		foreach ($this->result as $key => $value) {
			# code...
			if($value['fileStatus']==false){
				$str.=$value['filePath'].$value['fileName'].',<br>'."\n";
			}
		}
		if($this->checkPass==false){
			if($arr['forceUpdate']=='no'){
				$this->false("有重复文件,请检查排除后,提交,文件如下 <br> "."\n".$str ."\n"."如需 强制更新 请在说明 字段 加入 {forceUpdate}");
			}
			
		}
	
		 
	}

   /**
    　* 驼峰命名转下划线命名
    　* 思路:
    　* 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
    　*/
    public function uncamelize($camelCaps, $separator='_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }
	/* 
	*  @desc      检查是否表存在
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/08 10:44:50  
	*/ 
	public function  checkSql(array $arr)
	{
		//do somehing
		$table=$this->uncamelize($arr['table']['tableName']);
		//halt($arr['table']['tableName']);
		//$table='teacher';
		$sql='show tables like "'.$table.'"';
		//halt($sql);
		$exist = $this->app->db->query($sql);

		if($exist){
			
			if(isset($arr['table']['override']) and $arr['table']['override']=='yes'){
				$this->insertSql($arr);
			}else{
				$this->false("数据库 表 ".$table."已经存在 ,请删除 或者在说明字段 加入{override}  即可强制覆盖表 "."\n");
			}
		}

		if(!$exist){
			//halt($arr);
			$this->insertSql($arr);
		}


		

		//$this->false("数据库 表 ".$table."已经存在 ,请删除 或者勾选强制覆盖表 "."\n");
		//halt($exist); 
	}


	/* 
	*  @desc      插入数据
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/08 14:53:50  
	*/ 
	public function  insertSql(array $arr)
	{
		//do somehing
		//halt($arr['run']["sql"]);
		//exit($arr['run']["sql"]);
	
		foreach ($arr['run']['sql'] as $key => $value) {
			$this->app->db->query($value); 
		}
		$this->bakSql($arr);
		$this->bakMarkdown($arr);
		//$this->sqlResult=$exist ;
	}


	/* 
	*  @desc      备份sql
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/08 15:16:09  
	*/ 
	public function  bakSql(array $arr)
	{
		//有文件存在则 进行时间戳命名
		$path=$arr['forcePath']??'api';
		$arr['fileName']=$arr['table']['tableName']."_".$arr['timestamp'].'.sql';
		$arr['filePath']=$this->basePath."/app\/".$path."\/sql/";
		$arr['fileCon']=$arr['run']['sql']['main'];
		$this->checkDir($arr['filePath']);

		

		
		$this->buildFile($arr);
		//没有文件夹则创建文件夹
		 
	}

	//备份markdown
	/* 
	*  @desc      备份sql
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/08 15:16:09  
	*/ 
	public function  bakMarkdown(array $arr)
	{
		//有文件存在则 进行时间戳命名
		$path=$arr['forcePath']??'api';
		$arr['fileName']=$arr['table']['tableName']."_".$arr['timestamp'].'.md';
		$arr['filePath']=$this->basePath."/app\/".$path."\/md/";
		$arr['fileCon']=$arr['main'];
		$this->checkDir($arr['filePath']);

		

		
		$this->buildFile($arr);
		//没有文件夹则创建文件夹
		 
	}

	/* 
	*  @desc      返回失败信息
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/08 10:11:00  
	*/ 
	public function  false(string $string)
	{
		$arr['code']=0;
		$arr['msg']=$string;

		exit(json_encode($arr));
		 
	}


	/* 
	*  @desc      check 检查文件是否存在
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 14:43:08  
	*/ 
	public function  checkFile($url)
	{
		//do somehing
		//遍历文件 然后有文件就返回错误 
		if(file_exists($url)){
			//$this->faile('失败 '.$url.' 文件已存在');
			//$this->checkResult[]=$url;
			$this->checkPass=false;
			return false;
		} 
		return true;

	}


	/* 
	*  @desc      检查文件夹是否存在
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 17:55:40  
	*/ 
	public function  checkDir($dir)
	{
		if(!is_dir($dir)){
			mkdir($dir, 0755, true);
		}
		 
	}

	/* 
	*  @desc      buildFileTest
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 23:14:49  
	*/ 
	public function  buildFileAll()
	{
		//halt($this->result);
		foreach ($this->result as $key => $value) {
			$this->buildFile($value);
		}
		
		 
	}

	/* 
	*  @desc      创建控制器
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 15:26:22  
	*/ 
	public function  buildController(array $arr)
	{
		
		$file['fileName']=$arr['fileNames']['controller']['name'].'.php';
		$file['filePath']=$this->basePath.$arr['fileNames']['controller']['path'];
		$file['fileCon']=$arr['run']['controller'];
		$file['fileStatus']=$this->buildFileTest($file);
		$this->result['controller']=$file;
		
		 
	}

	/* 
	*  @desc      创建服务
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 15:26:22  
	*/ 
	public function  buildService(array $arr)
	{
			
		$file['fileName']=$arr['fileNames']['service']['name'].'.php';
		$file['filePath']=$this->basePath.$arr['fileNames']['service']['path'];
		$file['fileCon']=$arr['run']['service'];
		$file['fileStatus']=$this->buildFileTest($file);
		$this->result['service']=$file;
		
		 
	}


	/* 
	*  @desc      创建swagger的schema 说明
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 15:27:29  
	*/ 
	public function  buildSchema(array $arr)
	{
		$file['fileName']=$arr['fileNames']['schema']['name'].'.php';
		$file['filePath']=$this->basePath.$arr['fileNames']['schema']['path'];
		$file['fileCon']=$arr['run']['schema'];
		$file['fileStatus']=$this->buildFileTest($file);
		$this->result['schema']=$file;
		
		 
	}

	/* 
	*  @desc      创建api
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 15:27:55  
	*/ 
	public function  buildApi(array $arr)
	{
		$file['fileName']=$arr['fileNames']['api']['name'].'.php';
		$file['filePath']=$this->basePath.$arr['fileNames']['api']['path'];
		$file['fileCon']=$arr['run']['api'];
		$file['fileStatus']=$this->buildFileTest($file);
		$this->result['api']=$file;
		
		 
	}

	/* 
	*  @desc      创建视图
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 15:28:30  
	*/ 
	public function  buildView(array $arr,string $name)
	{
		//halt($arr);
		$file['fileName']=$name.'.html';
		$file['filePath']=$this->basePath.$arr['fileNames']['view']['path'].'/'.$arr['fileNames']['view']['name'].'/';
		$file['fileCon']=$arr['run']['view'][$name]['val'];
		
		$file['fileStatus']=$this->buildFileTest($file);
		$this->result[$name]=$file;
		 
	}

	/* 
	*  @desc      buildFile
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 14:53:35  
	*/ 
	public function  buildFileTest(array $arr)
	{
		//$url = Env::get('root_path').'application/admin/test.txt';   //定义创建路径
		$this->checkDir($arr['filePath']);
		$url=$arr['filePath'].$arr['fileName'];
		return $this->checkFile($url);

		//$this->result[]=$arr;
		//$file = fopen($url,"w");
		//$content = $arr['fileCon'];
		//fwrite($file,$content);
		//fclose($file);
		
	}

		/* 
	*  @desc      buildFile
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/07 14:53:35  
	*/ 
	public function  buildFile(array $arr)
	{
		
		$url=$arr['filePath'].$arr['fileName'];
		$file = fopen($url,"w");
		$content = $arr['fileCon'];
		fwrite($file,$content);
		fclose($file);
	
	}






	/**
	 * 绑定数据表
	 * @var string
	 */
	public $table = 'Client';

	/**
	* 首页
	* @date      2021-07-07 02:30:19
	* @auth true
	* @menu true
	* @login true
	* @throws \think\Exception
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
    */ 
	public function index() {
        
		$this->basePath=root_path();	
		$con=input('data');
		 
		$this->checkPass=true;
		$data=json_decode($con,true);
		//halt($data);
		//检查重复
		//$this->check($data);
		//构建
		$this->build($data);
		//halt($data);
		//exit(json_encode($this->result)); 
		if($data['forceUpdate']=='yes'){
			$this->success1('<b>强制</b> 生成成功!<br> 请到后台 系统管理菜单查看<br>,若在服务器端生成 请注意在服务器进行git更新操作 避免冲突,建议在本地环境进行操作 方便版本控制', $this->result);
		}
		$this->success1('生成成功! <br>请到后台 系统管理菜单查看,<br>若在服务器端生成 请注意在服务器进行git更新操作 避免冲突,建议在本地环境进行操作 方便版本控制', $this->result);
		
	}

	/* 
	*  @desc      成功
	*  @author    saruri <saruri@163.com>
	*  @date      2021/07/08 16:09:52  
	*/ 
	public function  success1($msg,$arr)
	{
		//do somehing
		$arr['code']=1;
		$arr['msg']=$msg;
		 exit(json_encode($arr));
	}



}
